import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from "../views/Login";
import Index from "../views/Index"
import axios from "../axios";
import store from '../store'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home,
        children: [
            {
                path: '/index',
                name: 'Index',
                component: Index,
                meta: {
                    title: "首页"
                }
            }
        ]
    },
    {
        path: "/login",
        name: "Login",
        component: Login,
    }
];

const router = new VueRouter({
    base: 'library-management-vue',
    routes
})

router.beforeEach((to, from, next) => {
    let hasRoute = store.state.hasRoute;
    let token = localStorage.getItem("token");
    if (to.path === '/login') {
        next()
    } else if (!token) {
        next({path: "/login"})
    } else if (to.path === '/' || to.path === '') {
        next({name: "Index"})
    } else if (!hasRoute) {
        axios.get("/sys/menu/nav").then(res => {
            store.commit("setNavList", res.data.data.nav);
            store.commit("setPermList", res.data.data.perms);
            let newRoutes = router.options.routes;

            res.data.data.nav.forEach(menu => {
                if (menu.type === 1) {
                    let route = menuToRoute(menu);
                    if (route) {
                        newRoutes[0].children.push(route);
                    }
                } else if (menu.type === 0 && menu.children) {
                    menu.children.forEach(e => {
                        let route = menuToRoute(e);
                        if (route) {
                            newRoutes[0].children.push(route);
                        }
                    })
                }
            });
            selfAddRoutes(newRoutes);
            store.commit("changeHasRoute", true);
        })

    }
    next()
})
;

const menuToRoute = menu => {
    if (!menu.component) {
        return null
    }
    return {
        path: menu.path,
        name: menu.name,
        component: () => import('@/views/' + menu.component + '.vue'),
        meta: {
            icon: menu.icon,
            title: menu.title
        }
    };
};

function selfAddRoutes(params) {
    router.matcher = new VueRouter({
        base: 'library-management-vue'
    }).matcher;
    router.addRoutes(params)
}

export default router
